﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Zeus.Thunder.Core;

namespace SharpTrainer.Concurrency
{
    class AsynDownloadWebTest : ITestCase
    {
        public void Run()
        {
            string url = @"http://www.apress.com";

            Task<string> downloadTask = DownloadWebPageAsync(url);
            int i = 1;
            while (!downloadTask.IsCompleted)
            {
                if (i++ % 50 == 0)
                    Console.WriteLine();
                else
                    Console.Write(".");

                Thread.Sleep(250);
            }

            Console.WriteLine(downloadTask.Result);
        }

        private string DownloadWebPage(string url)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            var reader = new StreamReader(response.GetResponseStream());
            {
                // this will return the content of the web page
                return reader.ReadToEnd();
            }
        }

        private Task<string> DownloadWebPageAsync(string url)
        {
            return Task.Factory.StartNew(() => DownloadWebPage(url));
        }
    }
}
